package handler

import (
	"encoding/json"
	"io"
	"net/http"

	"gitee.com/sheldwu/httpdns/config"
	"gitee.com/sheldwu/httpdns/util"
)

type cabinetResponseT struct {
	MqttList      []string `json:"mqtt_list"`
	HttpDnsList   []string `json:"httpdns_list"`
	RetryInternal int      `json:"retry_internal"`
}

type cabinetDebugResponseT struct {
	MqttList      []string `json:"mqtt_list"`
	HttpDnsList   []string `json:"httpdns_list"`
	RetryInternal int      `json:"retry_internal"`
	RequestIp     string   `json:"request_ip"`
	Province      string   `json:"province"`
	IDC           string   `json:"idc"`
	Provider      string   `json:"provider"`
}

func Cabinet(w http.ResponseWriter, req *http.Request) {
	req.ParseForm()

	var mqttList []string

	httpDnsList := util.SortByWeight(config.HttpDnsList)

	net, error := util.GetNet(req)

	province := "unknown"
	ip := "unknown"
	provider := "unknown"
	var idc string

	// 判断网络情况失败,使用默认的idc
	if error != nil {
		mqttList = util.SortMqttList(config.DefaultIdc)
	} else {
		//G网
		if net == util.GNet {
			iccid, err := util.GetIccid(req)
			if err != nil {
				idc = config.DefaultIdc
			} else {
				idc, province, provider = util.GetIdcByIccid(iccid)
			}
			// wifi
		} else {
			ip = util.GetIp(req)

			idc, province = util.GetIdcByIp(ip)
		}
		mqttList = util.SortMqttList(idc)
	}
	var responseByte []byte
	if !util.IsdebugMode(req) {
		var res cabinetResponseT

		res.MqttList = mqttList
		res.HttpDnsList = httpDnsList
		res.RetryInternal = config.RetryInternal
		responseByte, _ = json.Marshal(&res)
	} else {
		var res cabinetDebugResponseT

		res.MqttList = mqttList
		res.HttpDnsList = httpDnsList
		res.RetryInternal = config.RetryInternal
		res.Province = province
		res.RequestIp = ip
		res.IDC = idc
		res.Provider = provider
		responseByte, _ = json.Marshal(&res)
	}
	io.WriteString(w, string(responseByte))
	return
}
